<template>
  <div class="table-box" style="height: auto">
    <div class="table-search">
      <el-form :inline="true" :model="form">
        <el-form-item>
          <el-select
            clearable
            v-model="form.merchant_id"
            placeholder="商户"
            filterable
          >
            <el-option
              v-for="item in payMerchantList"
              :key="item.value"
              :label="item.name + '-' + item.merchant_id"
              :value="item.merchant_id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item>
          <el-input
            clearable
            placeholder="商户ID"
            v-model="form.merchant_id"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-input
            clearable
            placeholder="商户名称"
            v-model="form.merchant_name"
          ></el-input>
        </el-form-item> -->
        <el-form-item>
          <el-input
            clearable
            placeholder="订单流水号"
            v-model="form.order_no"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-input
            clearable
            placeholder="充值金额"
            v-model="form.amount"
          ></el-input>
        </el-form-item>
        <el-form-item label="审核结果">
          <el-select clearable v-model="form.audit_status" style="width: 120px">
            <el-option
              v-for="item in auditStatus"
              :key="item.value"
              :label="item.name"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="币种">
          <el-select
            v-model="form.currency"
            placeholder="币种"
            clearable
            style="width: 120px"
          >
            <el-option
              v-for="item in currencyList"
              :key="item.name"
              :label="item.alias"
              :value="item.name"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="添加时间">
          <el-date-picker
            clearable
            v-model="form.timeData"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="截止日期"
            :default-time="pickerDefaultTime"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onQuery">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="card content-box">
      <div class="table" style="height: auto">
        <el-table :data="tableData" border v-loading="loading">
          <el-table-column
            prop="send_pay_time"
            :formatter="formatterTime"
            label="充值日期"
            align="center"
            width="180"
          />
          <el-table-column
            prop="receive_actual_time"
            :formatter="formatterTime"
            label="银行到账时间"
            align="center"
            width="180"
          />
          <el-table-column prop="merchant_name" label="商户名称" align="center">
            <template #default="scope">
              <el-tooltip
                class="box-item"
                effect="dark"
                :content="scope.row.merchant_name"
                :disabled="!scope.row.merchant_name"
                placement="top"
              >
                <span class="ellipsis">{{
                  scope.row.merchant_name || "--"
                }}</span>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column prop="amount" label="充值金额" align="center">
            <template #default="scope">{{
              numberToCurrencyNo(scope.row.amount)
            }}</template>
          </el-table-column>
          <el-table-column
            prop="fee"
            label="手续费"
            align="center"
          ></el-table-column>
          <el-table-column prop="currency" label="充值币种" align="center" />
          <el-table-column
            prop="actual_amount"
            label="银行到账金额"
            align="center"
          >
            <template #default="scope"
              >{{ numberToCurrencyNo(scope.row.actual_amount) }}
            </template>
          </el-table-column>
          <el-table-column
            width="150"
            prop="receive_name"
            label="收款姓名"
            align="center"
          >
            <template #default="scope">
              <el-tooltip
                class="box-item"
                effect="dark"
                :content="scope.row.receive_name"
                :disabled="!scope.row.receive_name"
                placement="top"
              >
                <span class="ellipsis">{{
                  scope.row.receive_name || "--"
                }}</span>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="订单状态" align="center">
            <!--0:处理中;1:成功;2:失败 3:取消-->
            <template #default="scope">
              <el-tag
                :type="
                  scope.row.status == 1
                    ? 'success'
                    : scope.row.status == 0
                    ? 'warning'
                    : 'danger'
                "
              >
                {{
                  scope.row.status == 1
                    ? "成功"
                    : scope.row.status == 2
                    ? "失败"
                    : scope.row.status == 3
                    ? "取消"
                    : "处理中"
                }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
            prop="sys_review_status"
            label="系统审核"
            align="center"
          >
            <template #default="scope">
              <el-tag
                :type="
                  scope.row.sys_review_status == 1
                    ? 'success'
                    : scope.row.sys_review_status == 0
                    ? 'warning'
                    : 'danger'
                "
              >
                {{
                  scope.row.sys_review_status == 1
                    ? "已审核"
                    : scope.row.sys_review_status == 2
                    ? "拒绝"
                    : "未审核"
                }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="invoice_desc" label="开票" align="center" />
          <el-table-column prop="description" label="备注" align="center" />
          <el-table-column
            label="操作"
            align="center"
            fixed="right"
            width="180"
          >
            <template #default="scope">
              <el-button
                type="danger"
                size="small"
                v-if="
                  scope.row.sys_review_status === 0 &&
                  scope.row.allow_review === 1
                "
                @click="handleOperate(scope.$index, scope.row, 'audit')"
                >审核</el-button
              >
              <el-button
                type="info"
                size="small"
                @click="handleOperateInvoice(scope.row)"
                >开票</el-button
              >
              <el-button
                type="info"
                size="small"
                @click="handleOperateDesc(scope.row)"
                >备注</el-button
              >
              <el-button
                type="primary"
                size="small"
                @click="handleOperate(scope.$index, scope.row, 'detail')"
                >详情</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <div class="table-pagination">
          <el-pagination
            :current-page="pageable.pageNum"
            :page-size="pageable.pageSize"
            :page-sizes="[10, 20, 50]"
            :background="true"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pageable.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          ></el-pagination>
        </div>
      </div>
    </div>
    <DrawerDetail
      :drawerVisible="drawerVisible"
      @close="close"
      :detailInfo="detailInfo"
      @handleOperate="handleOperate"
      :auditHistory="auditHistory"
    ></DrawerDetail>
    <DialogForm
      @cancel="cancel"
      @closeDialog="closeDialog"
      @submitForm="submit"
      :auditHistory="auditHistory"
      :dialogFormVisible="dialogVisible"
      :dialogForm="dialogForm"
      :btnLoading="btnLoading"
      :dialogTitle="dialogTitle"
      :btnType="btnType"
    />
    <el-dialog v-model="descVisible" :title="descTitle" width="500">
      <el-form :model="descForm">
        <el-form-item label="备注">
          <el-input v-model="descForm.description" type="textarea" rows="5" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="descVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="submitDesc(descForm)"
            :loading="btnLoading"
          >
            提交
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, computed } from "vue";
import {
  formatterTime,
  pickerDefaultTime,
  timestamp,
  numberToCurrencyNo,
} from "@/utils/utils";
import {
  reviewRechargeOrderApi,
  reviewRechargeAuditApi,
  reviewHistoryApi,
  setOrderDescApi,
  setOrderInvoiceApi,
} from "@/api/payServerse/review";
import { assetsCurrencyApi } from "@/api/payServerse/settings";
import DialogForm from "./components/auditForm.vue";
import DrawerDetail from "./components/detailDrawer.vue";
import { GlobalStore } from "@/store";

const globalStore = GlobalStore();
const payMerchantList = computed(() => globalStore.payMerchantList);
const loading = ref(false);
const tableData = ref([]);
const auditStatus = ref([]);
const auditHistory = ref([]);
const dialogVisible = ref(false);
const dialogTitle = ref("");
const btnLoading = ref(false);
const drawerVisible = ref(false);
const btnType = ref("");
const currencyList = ref([]);

const formData = {
  merchant_id: "",
  merchant_name: "",
  order_no: "",
  audit_status: "",
  currency: "",
  amount: "",
  timeData: [],
};
const form = reactive({ ...formData });
const dialogFormData = {
  audit_order_id: "",
  order_no: "",
  review_status: "",
  review_reason: "",
  payment_image: "",
  payment_image_show: "",
  amount: "",
  currency: "",
  actual_recharge_amount: "",
  receive_actual_time: "",
};
const dialogForm = reactive({ ...dialogFormData });
const pageable = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0,
});

const detailInfo = ref({});
const descVisible = ref(false);

const descForm = reactive({
  order_no: "",
  description: "",
});

const type = ref("");
const descTitle = ref("设置备注");
//参数
const param = () => {
  return {
    page: pageable.pageNum,
    pagesize: pageable.pageSize,
    merchant_id: form.merchant_id,
    merchant_name: form.merchant_name,
    order_no: form.order_no,
    audit_status: form.audit_status,
    amount: form.amount,
    currency: form.currency,
    start: form.timeData[0] ? timestamp(form.timeData[0].valueOf()) : "",
    end: form.timeData[1] ? timestamp(form.timeData[1].valueOf()) : "",
  };
};

// 获取表格数据
const getTableData = async () => {
  loading.value = true;

  try {
    const res = await reviewRechargeOrderApi(param());
    loading.value = false;
    tableData.value = res.data.results;
    pageable.total = res.data.count;
    auditStatus.value = res.data.extra.audit_status;
  } catch (error) {
    loading.value = false;
  }
};
//查询
const onQuery = async () => {
  getTableData();
};
// 行操作
const handleOperate = async (index, row, type) => {
  // 编辑
  if (type === "audit") {
    btnType.value = "audit";
    dialogTitle.value = "订单审核";
    Object.assign(dialogForm, {
      //...row
      audit_order_id: row.audit_order_id,
      order_no: row.order_no,
      amount: row.amount,
      currency: row.currency,
      review_status: "",
      payment_image: "",
      payment_image_show: "",
      fileList: [],
      warning: row.warning,
      warning_msg: row.warning_msg,
      warning_result: false,
    });
    dialogVisible.value = true;
  } else if (type === "detail") {
    drawerVisible.value = true;
    detailInfo.value = row;
  }
  const his = await reviewHistoryApi({ order_id: row.audit_order_id });
  auditHistory.value = his.data.results;
};
const handleOperateDesc = async (row) => {
  // 编辑
  descVisible.value = true;
  Object.assign(descForm, {
    order_no: row.order_no,
    description: row.description,
  });
  type.value = "desc";
  descTitle.value = "设置备注";
};
const handleOperateInvoice = async (row) => {
  // 编辑
  descVisible.value = true;
  Object.assign(descForm, {
    order_no: row.order_no,
    description: row.invoice_desc,
  });
  type.value = "invoice";
  descTitle.value = "开票";
};

const close = () => {
  drawerVisible.value = false;
};

// 提交
const submit = async (param) => {
  try {
    btnLoading.value = true;
    if (
      param.warning_result !== 1 &&
      param.review_status == 1 &&
      param.warning === 2
    ) {
      ElMessage({
        type: "error",
        message: "请勾选警告信息",
      });
      btnLoading.value = false;
      return false;
    }
    if (!param.payment_image && param.review_status == 1) {
      ElMessage({
        type: "error",
        message: "请上传收款凭证图片",
      });
      btnLoading.value = false;
      return false;
    }
    let res;
    res = await reviewRechargeAuditApi(param);
    ElMessage({
      message: res.message,
      type: "success",
    });
    dialogVisible.value = false;
    btnLoading.value = false;
    getTableData();
  } catch (error) {
    btnLoading.value = false;
    //        dialogVisible.value = false;
  }
};
// 提交
const submitDesc = async (param) => {
  try {
    btnLoading.value = true;
    if (!param.description) {
      ElMessage({
        type: "error",
        message: "请填写备注",
      });
      btnLoading.value = false;
      return false;
    }
    let res;
    if (type.value == "desc") {
      res = await setOrderDescApi(param);
    } else {
      res = await setOrderInvoiceApi(param);
    }
    ElMessage({
      message: res.message,
      type: "success",
    });
    descVisible.value = false;
    btnLoading.value = false;
    getTableData();
  } catch (error) {
    btnLoading.value = false;
  }
};
//关闭弹窗
const closeDialog = () => {
  dialogVisible.value = false;
  btnType.value = null;
  Object.assign(dialogForm, { ...dialogFormData });
};

// 取消
const cancel = () => {
  dialogVisible.value = false;
  btnType.value = null;
  Object.assign(dialogForm, { ...dialogFormData });
};

// 条数
const handleSizeChange = (number) => {
  pageable.pageSize = number;
  getTableData();
};
// 页码
const handleCurrentChange = (number) => {
  pageable.pageNum = number;
  getTableData();
};

// 获取币种
const getCurrencyList = async () => {
  try {
    const res = await assetsCurrencyApi({});
    currencyList.value = res.data.results;
  } catch (error) {
    currencyList.value = [];
  }
};

onMounted(() => {
  getTableData();
  getCurrencyList();
});
</script>
